﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using NewAI.Client;
namespace NewAI.FSM.SocketConnectFSM
{
    public class AIClientSocket : IBaseEntity
    {
        public State<AIClientSocket> CurrentState { set; get; }

        public string Host { set; get; }
        public int Port { set; get; }
        public ServerConnector ClientSocket { set; get; }
        public String ActionJson { set; get; }
        public FSMMessage ReceiveGameServerDataMessage = new FSMMessage();
        public bool WillClose { set; get; } = false;

        public AIClientSocket(string host, int port, TeamInfo teamInfo)
        {
            Host = host;
            Port = port;
            GV.OurTeam = teamInfo;
            PubliceMessage.CloseAllMessage.OnEvent += OnCloseAll;
            ChangeState(new ConnectToGameServerState());
        }

        public void OnSocketException(object sender, ServerConnectorEventArgs args)
        {
            WillClose = true;
            PubliceMessage.SocketException.Call(sender, new FSMEventEventArg(args.Msg), null);
        }

        public void OnReceiveData(object sender, ServerConnectorEventArgs args)
        {
            ChangeState(new ReceiveGameServerMsgState(args.Msg));
        }

        public void OnReceiveActionJson(object sender, FSMEventEventArg args)
        {
            ChangeState(new SendMsgToGameServerState(args.Msg));
        }

        private void OnCloseAll(object sender, FSMEventEventArg e)
        {
            WillClose = true;
            if (CurrentState != null)
                CurrentState.Exit(this);
            if (ClientSocket != null)
                ClientSocket.Close();
            CurrentState = null;
        }

        public void ChangeState(State<AIClientSocket> state)
        {
            if (CurrentState != null)
                CurrentState.Exit(this);
            CurrentState = state;
            CurrentState.Enter(this);
        }

        public void Update()
        {
            CurrentState.Execute(this);
        }
    }
}
